package hz.mobileproject.pda.toolsmanager.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsScrapLVAdaper;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsStockAdapter;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_FreeCountTool;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_SelToolInfo;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ToolsScrap;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_FreeCountTools;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.toolsmanager.utils.ToolCommonHttpUtils;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_tools_scrap)
public class ToolsScrapActivity extends BaseScanActivity {
    @ViewInject(R.id.lv_tools_scrap)
    private ListView lv_tools_scrap;
    @ViewInject(R.id.lv_tools_stock)
    private ListView lv_tools_stock;
    @ViewInject(R.id.tv_policeName)
    private TextView tv_policeName;
    @ViewInject(R.id.tv_showTime)
    private TextView tv_showTime;

    private Gson mGson;
    private ToolsScrapLVAdaper mToolsScrapLVAdaper;
    private ToolsStockAdapter mToolsStockAdapter;
    private RP_ToolSysSet mToolSystemSet;
    //当前民警信息
    private Response_loadPoliceInfo mPoliceInfo;

    private Set<String> mAlreadyScrapTools;

    private static final int REQUEST_CODE_POLICE = 0x1011;
    private static final int REQUEST_CODE_TOOLS = 0x1014;

    @Override
    protected void initData() {
        setTitleText("工具报废");
        mGson = new Gson();
        tv_showTime.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd")));
        mToolsScrapLVAdaper = new ToolsScrapLVAdaper(this, new ArrayList<RP_ToolInfo>());
        lv_tools_scrap.setAdapter(mToolsScrapLVAdaper);
        mToolsStockAdapter = new ToolsStockAdapter(this, new ArrayList<RP_FreeCountTools>());
        lv_tools_stock.setAdapter(mToolsStockAdapter);
        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        mAlreadyScrapTools = new HashSet<>();
        //扫描民警
        scanPolice();
    }

    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_TOOLS:
                getToolInfoFromSer(scanMsg);
                break;
        }
    }


    @Event({R.id.btn_tools_scrap_complete})
    private void onViewClick(View v){
        switch (v.getId()) {
            case R.id.btn_tools_scrap_complete:
                scrapToolsToSer();
                break;
        }
    }



    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPoliceInfoFromSer(scanStr, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
                if (loadPoliceInfo == null) {
                    ToastUtils.showLong("民警信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPoliceInfo = loadPoliceInfo;
                tv_policeName.setText(mPoliceInfo.getPolice_name());
                //获取库存信息
                getFreeToolsCountFromSer();
                //打开扫描
                scanTools();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取民警信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取民警信息失败");
                LogUtils.e(ex);
            }
        });
    }




    /**
     * 请求网络接口获取库存信息
     */
    private void getFreeToolsCountFromSer() {
        ToolCommonHttpUtils.getFreeToolsCountFromSer(mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_FreeCountTools> tempList = mGson.fromJson(data, new TypeToken<ArrayList<RP_FreeCountTools>>() {
                }.getType());
                mToolsStockAdapter.clearAdd(tempList);
                if (tempList == null || tempList.size() == 0) {
                    ToastUtils.showLong("库存信息为空");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取库存信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取库存信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取工具信息
     *
     * @param scanStr
     */
    private void getToolInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getToolInfoFromSer(scanStr,mToolSystemSet,mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                RP_ToolInfo toolInfo = mGson.fromJson(data, RP_ToolInfo.class);
                if (toolInfo == null) {
                    ToastUtils.showLong("工具信息格式错误或为空");
                    return;
                }
                //判断工具是否借来的
                if(toolInfo.getBorrow_status() == RP_ToolInfo.BORROW_STATUS_ISBORROW){
                    ToastUtils.showLong("借入工具请归还原部门提交报废");
                    return;
                }
                //判断工具是否报废
                if(toolInfo.getStatus() == RP_ToolInfo.STATUS_SCRAP){
                    ToastUtils.showLong("此工具已被报废");
                    return;
                }
                //判断此工具是否已在发放列表
                if(mAlreadyScrapTools.contains(toolInfo.getTool_id())){
                    ToastUtils.showLong("此工具已存在列表中");
                    return;
                }
                mAlreadyScrapTools.add(toolInfo.getTool_id());
                mToolsScrapLVAdaper.add(toolInfo);
                lv_tools_scrap.setSelection(mToolsScrapLVAdaper.getCount());
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取工具信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取工具信息失败");
                LogUtils.e(ex);
            }
        });
    }

    /**
     * 提交工具报废
     */
    private void scrapToolsToSer() {
        List<RQ_ToolsScrap> toolsList = new ArrayList<>();
        for(int i=0;i<mToolsScrapLVAdaper.getCount();i++){
            RQ_ToolsScrap rq_toolsScrap = new RQ_ToolsScrap();
            rq_toolsScrap.setCus_number(mPoliceInfo.getCus_number());
            rq_toolsScrap.setTool_id(mToolsScrapLVAdaper.getItem(i).getTool_id());
            toolsList.add(rq_toolsScrap);
        }
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_SCRAP_TOOLS, toolsList, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                new AlertDialog.Builder(ToolsScrapActivity.this).setTitle("提示")
                        .setMessage("工具报废提交成功，本页面将关闭")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ToolsScrapActivity.this.finish();
                            }
                        }).setCancelable(false).create().show();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("工具报废提交失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("工具报废提交失败");
                LogUtils.e(ex.toString());
            }
        });
    }


    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == mToolSystemSet.getCall_type()) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描民警条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == mToolSystemSet.getCall_type()) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            //获取库存信息
            getFreeToolsCountFromSer();
            //接着扫描
            scanTools();
        }
    }

    private void scanTools() {
        if (RP_ToolSysSet.TSS_SWEEP_TYPE_CAMERA == mToolSystemSet.getSweep_type()) {
            setTitleRightIcon(true, R.mipmap.scan_camera);
            getIv_title_right().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //请扫描工具
                    openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描工具");
                }
            });
        }

        //请扫描工具
        openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描工具");
    }
}
